package com.cn.ccp.action.course;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.cn.ccp.action.BaseAction;
import com.cn.ccp.bean.CourseBean;
import com.cn.ccp.bean.CourseOutlineBean;
import com.cn.ccp.bean.FilePathBean;
import com.cn.ccp.util.CCPContants;
import com.cn.ccp.util.Contants;

/**
 * 课程action
 * @author renyongcheng
 *
 */
public class CourseOutlineAction extends BaseAction{
	private Logger log = Logger.getLogger(CourseOutlineAction.class);
	private String courseId,courseName,courseOutline;//课程id
	private CourseOutlineBean outline;
	private String outlineFile;
	public CourseOutlineAction(){
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		if(varMap.get("id") != null){
			courseId = varMap.get("id");
			log.info("----------courseId = "+courseId);
			Object obj = getCourseService().getOutlineByCourseId(courseId);
			if(obj != null)
				outline = (CourseOutlineBean)obj;
			log.info(outline);
			CourseBean cb = getCourseService().getBeanById(courseId);
			courseName = cb.getCourse_name();
		}
	}
	
	public String uploadOutline(){
		log.info("-----------uploadOutline()-------- ");
		log.info("-------------------outlineFile =  "+outlineFile);
		
		String savePath = CCPContants.SYS_PATH+"files/"+ CCPContants.getCurrUserId() + "/" + courseId + "/" + Contants.OUTLINE_DERECT + "/";
		FilePathBean filePathBean =  getFilePathService().getFlagBean();
		if(filePathBean != null){
			savePath = filePathBean.getPath()+CCPContants.getCurrUserId() +"/" + courseId + "/" + Contants.OUTLINE_DERECT + "/";;
		} 
		log.info("-------------------savePath =  "+savePath);
		File[] f1 = new File(savePath).listFiles();
		if(f1 == null || f1.length <= 0){
			showMsg("uploadStudent", "user_page_label_upload_student_null_error");
			return "";
		}
		for(File f:f1) {
			try {
				log.info("------"+f.getCanonicalPath());
				if(!f.getName().equalsIgnoreCase(outlineFile))
					f.delete();
			} catch (IOException e) {
				log.error("delete failed ", e);
			}
		}
		log.info(outline);
//		if(getOutline().getId() != 0){
//			getCourseService().updateCourseOutline(outline.getId(), filePathBean.getId(),CCPContants.getCurrUserId() + "/" + courseId + "/" + Contants.OUTLINE_DERECT + "/" + outlineFile);
//		}else
		getCourseService().saveCourseOutline(courseId, filePathBean.getId(),CCPContants.getCurrUserId() + "/" + courseId + "/" + Contants.OUTLINE_DERECT + "/" + outlineFile);
		updateSessionPath(savePath+outlineFile);
		return MAIN;
	}
	
	
	private void updateSessionPath(String path){
		if(!path.endsWith(".txt")){
			File file  = new File(path);
			String fileName = file.getName();
			CCPContants.copyOutline(path, CCPContants.getCurrUserId() + "/" + courseId + "/" + Contants.OUTLINE_DERECT + "/" + fileName,Contants.OUTLINE_DERECT);
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			session.setAttribute(CCPContants.OUTLINE_FILE_PATH, CCPContants.getCurrUserId() + "/" + courseId + "/" + Contants.OUTLINE_DERECT + "/" + fileName);
		}
	}
	
	
	/**
	 * 保存公告
	 * @return
	 */
	public String commint(){
		log.info("------------------- "+outline);
		
		Object contents = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("content1");
		log.info("-------------------contents = "+contents);
		log.info("-------------------courseId = "+courseId);
		FilePathBean path = getFilePathService().getFlagBean();
		String savePath = CCPContants.SYS_PATH+"files"+File.separator  ;
		if(path != null){
			savePath = path.getPath() ;
		}
		if(outline.getId() != 0){//更新大纲文件内容
//			getCourseService().updateCourseOutline(outline.getId(), contents.toString());
			log.info(savePath);
			if(!outline.getOutline().endsWith(".txt")){
				String uuid = UUID.randomUUID().toString();
				String fileName = CCPContants.getCurrUserId()  + "/" +  uuid + ".txt";
				savePath +=  fileName;
				log.info(savePath);
//				getCourseService().updateCourseOutline(outline.getId(), path.getId(),fileName);
				getCourseService().saveCourseOutline(courseId, path.getId(),fileName);
			}else{
				savePath += outline.getOutline();
			}
		}else{	
			//将大纲内容写入txt文件
			String uuid = UUID.randomUUID().toString();
			String fileName = CCPContants.getCurrUserId()  + "/" +  uuid + ".txt";
			savePath +=  fileName;
			getCourseService().saveCourseOutline(courseId, path.getId(),fileName);
		}
		log.info(savePath);
		FileWriter fw = null;
		try {
			File file = new File(savePath);
			if(file.exists())
				file.deleteOnExit();
			file.createNewFile();
			fw = new FileWriter(savePath);
			fw.write(contents.toString(),0,contents.toString().length());    
			fw.flush();    
		} catch (IOException e) {
			log.error("save outline failed : ", e);
		} finally{
			try {
				if(fw != null)
					fw.close();
			} catch (IOException e) {
			}
		}   
		return MAIN;
	}
	
	public String back(){
		return MAIN;
	}


	public String getCourseId() {
		return courseId;
	}


	public void setCourseId(String courseId) {
		this.courseId = courseId;
	}

	public CourseOutlineBean getOutline() {
		if(outline == null)
			outline = new CourseOutlineBean();
		return outline;
	}

	public void setOutline(CourseOutlineBean outline) {
		this.outline = outline;
	}

	public String getCourseName() {
		return courseName;
	}

	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}

	private String getOutlineFilePath(){
		FilePathBean path = getFilePathService().getFlagBean();
		String savePath = CCPContants.SYS_PATH+"files"+File.separator ;
		if(path != null){
			savePath = path.getPath() ;
		}
		return savePath;
	}
	
	public String getCourseOutline() {
		if(outline != null){
			if(outline.getFilePathId() != 0){
				if(!outline.getOutline().endsWith(".txt"))
					return "";
				String savePath = getOutlineFilePath();
				savePath += outline.getOutline();
				log.info(savePath);
				FileReader fr = null;
				BufferedReader reader = null;
				StringBuffer buf = new StringBuffer();
				try {
					reader = new BufferedReader(new FileReader(savePath));
					String text = null;
					while ((text = reader.readLine()) != null){
						 buf.append(text);
						 buf.append(System.getProperty("line.separator"));
					}
					courseOutline = buf.toString();
				} catch (IOException e) {
					log.info("read outline failed : ",e);
				} finally{
					try {
						if(reader != null)
							reader.close();
					} catch (IOException e) {
					}
				} 
			}
			
		}
		
		return courseOutline;
	}

	public void setCourseOutline(String courseOutline) {
		this.courseOutline = courseOutline;
	}

	public String getOutlineFile() {
		return outlineFile;
	}

	public void setOutlineFile(String outlineFile) {
		this.outlineFile = outlineFile;
	}

	

	
}
